<template>
  <div class="element-comps">
    <!-- 单行文本 -->
    <template v-if="element.type === 'single-input'">
      <el-input
        :model-value="modelValue"
        :placeholder="element.options.placeholder"
        :disabled="element.options.disabled"
        :readonly="element.options.readonly"
        @update:modelValue="(val) => $emit('update:modelValue', val)"
        @change="(val) => $emit('change', val, element.id)"
      />
    </template>

    <!-- 多行文本 -->
    <template v-if="element.type === 'textarea'">
      <el-input
        type="textarea"
        :model-value="modelValue"
        :placeholder="element.options.placeholder"
        :disabled="element.options.disabled"
        :readonly="element.options.readonly"
        @update:modelValue="(val) => $emit('update:modelValue', val)"
        @change="(val) => $emit('change', val, element.id)"
      />
    </template>

    <!-- 数字输入 -->
    <template v-if="element.type === 'number'">
      <el-input-number
        :model-value="modelValue"
        :placeholder="element.options.placeholder"
        :disabled="element.options.disabled"
        :readonly="element.options.readonly"
        :min="element.options.minValue"
        :max="element.options.maxValue"
        @update:modelValue="(val) => $emit('update:modelValue', val)"
        @change="(val) => $emit('change', val, element.id)"
      />
    </template>

    <!-- 单选框组 -->
    <template v-if="element.type === 'radio'">
      <el-radio-group
        :model-value="modelValue"
        @update:modelValue="(val) => $emit('update:modelValue', val)"
        @change="(val) => $emit('change', val, element.id)"
      >
        <el-radio 
          v-for="option in element.options.selectOptions"
          :key="option.value"
          :label="option.value"
        >
          {{ option.label }}
        </el-radio>
      </el-radio-group>
    </template>

    <!-- 多选框组 -->
    <template v-if="element.type === 'checkbox'">
      <el-checkbox-group
        :model-value="modelValue"
        @update:modelValue="(val) => $emit('update:modelValue', val)"
        @change="(val) => $emit('change', val, element.id)"
      >
        <el-checkbox
          v-for="option in element.options.selectOptions"
          :key="option.value"
          :label="option.value"
        >
          {{ option.label }}
        </el-checkbox>
      </el-checkbox-group>
    </template>

    <!-- 下拉选择 -->
    <template v-if="element.type === 'select'">
      <el-select
        :model-value="modelValue"
        :placeholder="element.options.placeholder"
        :disabled="element.options.disabled"
        :multiple="element.options.multiple"
        @update:modelValue="(val) => $emit('update:modelValue', val)"
        @change="(val) => $emit('change', val, element.id)"
      >
        <el-option
          v-for="option in element.options.selectOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
    </template>

    <!-- 日期选择 -->
    <template v-if="element.type === 'date'">
      <el-date-picker
        :model-value="modelValue"
        :type="element.options.type"
        :placeholder="element.options.placeholder"
        :disabled="element.options.disabled"
        :format="element.options.format"
        :value-format="element.options.valueFormat"
        @update:modelValue="(val) => $emit('update:modelValue', val)"
        @change="(val) => $emit('change', val, element.id)"
      />
    </template>

    <!-- 标签页 -->
    <template v-if="element.type === 'tabs'">
      <el-tabs
        v-model="element.options.activeName"
        :type="element.options.type"
        :tab-position="element.options.tabPosition"
        class="form-tabs"
      >
        <el-tab-pane
          v-for="tab in element.options.tabs"
          :key="tab.name"
          :label="tab.label"
          :name="tab.name"
        >
          <draggable
            class="tab-content"
            :list="tab.list"
            group="form"
            item-key="id"
            animation="300"
            @add="(e) => handleTabAdd(e, tab)"
            @change="(e) => handleTabChange(e, tab)"
          >
            <template #item="{ element: tabElement }">
              <div class="tab-item">
                <element-comps
                  :element="tabElement"
                  :model-value="modelValue[tabElement.id]"
                  @update:modelValue="(val) => handleTabItemChange(val, tabElement.id)"
                  @change="(val) => $emit('change', val, tabElement.id)"
                />
              </div>
            </template>
            <template #footer>
              <div class="tab-placeholder">
                <el-icon><Plus /></el-icon>
                <span>拖拽组件到这里</span>
              </div>
            </template>
          </draggable>
        </el-tab-pane>
      </el-tabs>
    </template>

    <!-- 容器 -->
    <template v-if="element.type === 'container'">
      <div 
        class="form-container"
        :style="{ 
          padding: element.options.padding,
          background: element.options.background
        }"
      >
        <div v-if="element.options.showHeader" class="container-header">
          {{ element.options.title }}
        </div>
        <draggable
          class="container-content"
          :list="element.options.list"
          group="form"
          item-key="id"
          animation="300"
          @add="(e) => handleContainerAdd(e)"
          @change="(e) => handleContainerChange(e)"
        >
          <template #item="{ element: containerElement }">
            <div class="container-item">
              <element-comps
                :element="containerElement"
                :model-value="modelValue[containerElement.id]"
                @update:modelValue="(val) => handleContainerItemChange(val, containerElement.id)"
                @change="(val) => $emit('change', val, containerElement.id)"
              />
            </div>
          </template>
          <template #footer>
            <div class="container-placeholder">
              <el-icon><Plus /></el-icon>
              <span>拖拽组件到这里</span>
            </div>
          </template>
        </draggable>
      </div>
    </template>

    <!-- 动态表单 -->
    <template v-if="element.type === 'dynamic-form'">
      <div class="dynamic-form">
        <!-- 表头 -->
        <div v-if="element.options.showHeader" class="dynamic-form-header">
          {{ element.options.title }}
        </div>
        
        <!-- 表格 -->
        <el-table
          :data="tableData"
          border
          class="dynamic-form-table"
        >
          <!-- 序号列 -->
          <el-table-column
            v-if="element.options.showIndex"
            :label="element.options.indexLabel"
            type="index"
            width="60"
            align="center"
          />
          
          <!-- 动态列 -->
          <el-table-column
            v-for="col in element.options.columns"
            :key="col.prop"
            :label="col.label"
            :prop="col.prop"
            :width="col.width"
          >
            <template #default="{ row, $index }">
              <!-- 文本输入 -->
              <el-input
                v-if="col.type === 'single-input'"
                v-model="row[col.prop]"
                :placeholder="col.placeholder"
                @change="(val) => handleCellChange($index, col.prop, val)"
              />
              
              <!-- 下拉选择 -->
              <el-select
                v-else-if="col.type === 'select'"
                v-model="row[col.prop]"
                :placeholder="col.placeholder"
                @change="(val) => handleCellChange($index, col.prop, val)"
              >
                <el-option
                  v-for="option in col.options"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
              
              <!-- 数字输入 -->
              <el-input-number
                v-else-if="col.type === 'number'"
                v-model="row[col.prop]"
                :min="col.min"
                :max="col.max"
                :placeholder="col.placeholder"
                @change="(val) => handleCellChange($index, col.prop, val)"
              />
              
              <!-- 日期选择 -->
              <el-date-picker
                v-else-if="col.type === 'date'"
                v-model="row[col.prop]"
                :type="col.type"
                :format="col.format"
                :value-format="col.valueFormat"
                :placeholder="col.placeholder"
                @change="(val) => handleCellChange($index, col.prop, val)"
              />
            </template>
          </el-table-column>
          
          <!-- 操作列 -->
          <el-table-column
            label="操作"
            width="100"
            align="center"
            fixed="right"
          >
            <template #default="{ $index }">
              <el-button
                type="danger"
                link
                :disabled="tableData.length <= element.options.min"
                @click="handleDelete($index)"
              >
                {{ element.options.deleteButtonText }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 添加按钮 -->
        <div class="dynamic-form-footer">
          <el-button
            type="primary"
            :disabled="tableData.length >= element.options.max"
            @click="handleAdd(element)"
          >
            <el-icon><Plus /></el-icon>
            {{ element.options.addButtonText }}
          </el-button>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Plus, Delete, Close } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import { nanoid } from 'nanoid'
import dayjs from 'dayjs'

const props = defineProps({
  element: {
    type: Object,
    required: true
  },
  modelValue: {
    type: [String, Number, Boolean, Array, Object],
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

// 部门选择相关
const addModelVisible = ref(false)
const sections = ref([])

// 文件预览相关
const previewFile = ref(false)
const previewFileUrl = ref('')

// 处理文件上传
const handleSuccess = (response, uploadFile, uploadFiles) => {
  emit('update:modelValue', uploadFiles)
}

const handleRemove = (uploadFile, uploadFiles) => {
  emit('update:modelValue', uploadFiles)
}

const handlePreview = (uploadFile) => {
  previewFileUrl.value = uploadFile.url
  previewFile.value = true
}

// 处理部门选择
const selectSection = (arr) => {
  sections.value = arr
  addModelVisible.value = false
  emit('update:modelValue', sections.value)
}

const delSection = (section) => {
  const index = sections.value.findIndex(item => item.id === section.id)
  sections.value.splice(index, 1)
  emit('update:modelValue', sections.value)
}

// 日期禁用处理
const disabledDate = (time) => {
  if (props.disabledDate && props.minParentDate) {
    return time.getTime() < dayjs(props.minParentDate).valueOf()
  }
  return false
}

// 处理标签页组件添加
const handleTabAdd = (e, tab) => {
  if (e.added) {
    const element = e.added.element;
    // 深拷贝新元素，避免引用问题
    const newElement = JSON.parse(JSON.stringify(element));
    newElement.id = nanoid();
    e.added.element = newElement;
    
    // 初始化该组件的值
    emit('update:modelValue', {
      ...props.modelValue,
      [newElement.id]: newElement.options?.defaultValue
    });
  }
}

// 处理标签页组件变化
const handleTabChange = (e, tab) => {
  if (e.added || e.moved || e.removed) {
    // 通知父组件更新配置
    emit('change', props.modelValue)
  }
}

// 处理标签页内组件值变更
const handleTabItemChange = (value, id) => {
  emit('update:modelValue', {
    ...props.modelValue,
    [id]: value
  })
}

// 处理容器组件添加
const handleContainerAdd = (e) => {
  if (e.added) {
    const element = e.added.element;
    // 深拷贝新元素，避免引用问题
    const newElement = JSON.parse(JSON.stringify(element));
    newElement.id = nanoid();
    e.added.element = newElement;
    
    // 初始化该组件的值
    emit('update:modelValue', {
      ...props.modelValue,
      [newElement.id]: newElement.options?.defaultValue
    });
  }
}

// 处理容器组件变化
const handleContainerChange = (e) => {
  if (e.added || e.moved || e.removed) {
    // 通知父组件更新配置
    emit('change', props.modelValue)
  }
}

// 处理容器内组件值变更
const handleContainerItemChange = (value, id) => {
  emit('update:modelValue', {
    ...props.modelValue,
    [id]: value
  })
}

// 计算属性：处理动态表单的数据
const tableData = computed({
  get: () => props.modelValue || [],
  set: (value) => {
    emit('update:modelValue', value);
    emit('change', value, props.element.id);
  }
});

// 修改单元格值变更处理函数
const handleCellChange = (rowIndex, prop, value) => {
  const newData = [...tableData.value];
  newData[rowIndex] = {
    ...newData[rowIndex],
    [prop]: value
  };
  tableData.value = newData;
};

// 修改添加行处理函数
const handleAdd = (element) => {
  if (!element?.options?.columns) {
    return;
  }

  const newRow = element.options.columns.reduce((acc, col) => {
    switch (col.type) {
      case 'number':
        acc[col.prop] = col.defaultValue ?? 0;
        break;
      case 'select':
      case 'radio':
      case 'checkbox':
        acc[col.prop] = col.defaultValue ?? null;
        break;
      default:
        acc[col.prop] = col.defaultValue ?? '';
    }
    return acc;
  }, {});

  tableData.value = [...tableData.value, newRow];
};

// 修改删除行处理函数
const handleDelete = (index) => {
  const newData = [...tableData.value];
  newData.splice(index, 1);
  tableData.value = newData;
};

// 处理动态表单列的显示名称
const getColumnLabel = (column) => {
  // 如果有自定义标签名，优先使用
  if (column.label) {
    return column.label;
  }
  // 否则使用组件名称
  return column.name || '未命名';
};
</script>

<style lang="scss" scoped>
.element-comps {
  width: 100%;
}

.form-item {
  margin-bottom: 18px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-tabs {
  width: 100%;
  
  :deep(.el-tabs__content) {
    padding: 16px;
    background: #fff;
  }
  
  .tab-content {
    min-height: 100px;
    
    &.sortable-ghost {
      background: var(--el-color-primary-light-9);
      border: 1px dashed var(--el-color-primary);
      border-radius: 4px;
    }
  }
  
  .tab-item {
    margin-bottom: 18px;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 4px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .tab-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 16px;
    color: #909399;
    font-size: 13px;
    border: 1px dashed #e5e7eb;
    border-radius: 4px;
    
    &:hover {
      border-color: var(--el-color-primary);
      color: var(--el-color-primary);
    }
    
    .el-icon {
      font-size: 16px;
    }
  }
}

.form-container {
  width: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  
  .container-header {
    padding: 12px 16px;
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    border-bottom: 1px solid #e4e7ed;
  }
  
  .container-content {
    min-height: 100px;
    
    &.sortable-ghost {
      background: var(--el-color-primary-light-9);
      border: 1px dashed var(--el-color-primary);
      border-radius: 4px;
    }
  }
  
  .container-item {
    margin-bottom: 18px;
    padding: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .container-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 16px;
    color: #909399;
    font-size: 13px;
    border: 1px dashed #e5e7eb;
    border-radius: 4px;
    margin: 12px;
    
    &:hover {
      border-color: var(--el-color-primary);
      color: var(--el-color-primary);
    }
    
    .el-icon {
      font-size: 16px;
    }
  }
}

.dynamic-form {
  width: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  
  .dynamic-form-header {
    padding: 12px 16px;
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    border-bottom: 1px solid #e4e7ed;
  }
  
  .dynamic-form-table {
    width: 100%;
    
    :deep(.el-table__header) {
      th {
        background: #f8f9fa;
        color: #606266;
        font-weight: 500;
      }
    }
    
    :deep(.el-input),
    :deep(.el-select) {
      width: 100%;
    }
  }
  
  .dynamic-form-footer {
    padding: 16px;
    text-align: center;
    border-top: 1px solid #e4e7ed;
    
    .el-button {
      min-width: 120px;
    }
  }
}
</style>
